<template>
  <div class="app-container home">
    <!-- 问答模块 -->
    <div class="qa-container">
      <el-input 
        v-model="question" 
        placeholder="请输入您的问题" 
        class="question-input" 
        @keyup.enter.native="submitQuestion"
      >
        <template #append>
          <el-button type="primary" :loading="loading" @click="submitQuestion">
            提交
          </el-button>
        </template>
      </el-input>

      <div class="result-container">
        <div v-if="answer" class="answer-box">
          <h3>回答：</h3>
          <p>{{ answer }}</p>
        </div>
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
        <div v-if="loading" class="loading-text">
          正在努力思考中...
        </div>
      </div>
    </div>

    <!-- 任务列表模块 -->
    <div class="task-list-container">
      <div class="header-toolbar">
        <el-button 
          type="primary" 
          icon="el-icon-plus"
          @click="handleCreate"
        >
          新建任务
        </el-button>
      </div>

      <!-- 新建任务对话框 -->
      <el-dialog 
        title="新建任务" 
        :visible.sync="dialogVisible"
        width="600px"
        @closed="resetForm"
      >
        <el-form 
          ref="taskForm"
          :model="formData" 
          :rules="formRules"
          label-width="120px"
        >
          <el-form-item label="任务类型" prop="category">
            <el-select 
              v-model="formData.category" 
              placeholder="请选择任务类型"
              clearable
            >
              <el-option label="统计" :value="0" />
              <el-option label="预测" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="任务月份" prop="date">
            <el-date-picker
              v-model="formData.date"
              type="month"
              value-format="yyyyMM"
              placeholder="选择月份"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="包含PCDN" prop="containsPcdn">
            <el-radio-group v-model="formData.containsPcdn">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="任务附件" prop="file">
            <el-upload
              ref="upload"
              :limit="1"
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              accept=".zip"
            >
              <el-button size="small" type="primary">选择文件</el-button>
              <div slot="tip" class="el-upload__tip">
                请上传ZIP压缩文件（文件大小不超过10MB）
              </div>
            </el-upload>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            :loading="submitLoading"
            @click="submitTask"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>

      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="任务号">
          <el-input v-model="queryParams.id" placeholder="请输入任务号" clearable></el-input>
        </el-form-item>
        <el-form-item label="月份">
          <el-date-picker
            v-model="queryParams.date"
            type="month"
            value-format="yyyyMM"
            placeholder="选择月份"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="queryParams.category" placeholder="请选择" clearable>
            <el-option label="统计" :value="0"></el-option>
            <el-option label="预测" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 任务表格 -->
      <el-table
        :data="taskList"
        border
        style="width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column prop="id" label="任务号" width="100"></el-table-column>
        <el-table-column prop="category" label="类型" width="100">
          <template slot-scope="scope">
            {{ formatCategory(scope.row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="stateTagType(scope.row.state)">
              {{ formatState(scope.row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="月份" width="120"></el-table-column>
        <el-table-column prop="source" label="来源">
          <template slot-scope="scope">
            {{ formatSource(scope.row.source) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              :loading="scope.row.downloadLoading"
              @click="handleDownload(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 30]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        class="pagination-container"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "Index",
  data() {
    return {
      // 问答模块数据
      question: '',
      answer: '',
      loading: false,
      error: '',

      // 任务列表数据
      queryParams: {
        id: null,
        date: null,
        category: null
      },
      taskList: [],
      tableLoading: false,
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },

      // 新建任务数据
      dialogVisible: false,
      submitLoading: false,
      formData: {
        category: null,
        date: null,
        containsPcdn: null,
        file: null
      },
      formRules: {
        category: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        date: [
          { required: true, message: '请选择任务月份', trigger: 'change' }
        ],
        containsPcdn: [
          { required: true, message: '请选择是否包含PCDN', trigger: 'change' }
        ],
        file: [
          { required: true, message: '请上传任务附件', trigger: 'change' }
        ]
      }
    };
  },
  mounted() {
    this.fetchTaskList();
  },
  methods: {
    // 问答模块方法
    async submitQuestion() {
      if (!this.question.trim()) {
        this.error = '问题不能为空';
        return;
      }

      this.loading = true;
      this.error = '';

      try {
        const response = await axios.post('http://192.168.1.253:8080/api/v1/query', {
          question: this.question
        });

        if (response.data.code === 200) {
          this.answer = response.data.data;
        } else {
          this.error = response.data.msg || '请求失败，请稍后重试';
        }
      } catch (err) {
        this.error = '服务暂时不可用，请检查网络连接';
        console.error('API请求失败:', err);
      } finally {
        this.loading = false;
      }
    },

    // 任务列表方法
    async fetchTaskList() {
      this.tableLoading = true;
      try {
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...this.queryParams
        };
        
        // 过滤空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === null || params[key] === '') {
            delete params[key];
          }
        });

        const response = await axios.post('http://192.168.1.253:8080/api/v1/tasks/list', {
          params
        });

        if (response.data.code === 200) {
          this.taskList = response.data.data.records.map(item => ({
            ...item,
            downloadLoading: false
          }));
          this.pagination.total = response.data.data.total;
        } else {
          this.$message.error(response.data.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取任务列表失败:', error);
        this.$message.error('请求失败，请检查网络');
      } finally {
        this.tableLoading = false;
      }
    },

    // 新建任务方法
    handleCreate() {
      this.dialogVisible = true;
    },

    handleFileChange(file) {
      this.formData.file = file.raw;
      this.$refs.taskForm.validateField('file');
    },

    beforeUpload(file) {
      const isZip = [
        'application/zip',
        'application/x-zip-compressed',
        'application/octet-stream'
      ].includes(file.type) || file.name.split('.').pop() === 'zip';
      
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isZip) {
        this.$message.error('只支持ZIP格式');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB');
        return false;
      }
      return true;
    },

    handleExceed() {
      this.$message.warning('每次只能上传一个文件');
    },

    async submitTask() {
      this.$refs.taskForm.validate(async valid => {
        if (!valid) return;

        const formData = new FormData();
        formData.append('category', this.formData.category);
        formData.append('date', this.formData.date);
        formData.append('containsPcdn', this.formData.containsPcdn);
        formData.append('file', this.formData.file);

        this.submitLoading = true;
        try {
          const response = await axios.post('http://192.168.1.253:8080/api/v1/tasks', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });

          if (response.data.code === 200) {
            this.$message.success('任务创建成功');
            this.dialogVisible = false;
            this.fetchTaskList();
          } else {
            this.$message.error(response.data.msg || '任务创建失败');
          }
        } catch (error) {
          console.error('创建任务失败:', error);
          this.$message.error('请求失败，请检查网络');
        } finally {
          this.submitLoading = false;
        }
      });
    },

    resetForm() {
      this.$refs.taskForm.resetFields();
      this.$refs.upload.clearFiles();
      this.formData.file = null;
    },


    getFileNameFromHeaders(headers) {
      const contentDisposition = headers['content-disposition'];
      if (!contentDisposition) return null;
      
      const fileNameMatch = contentDisposition.match(/filename="?(.+?)"?$/);
      return fileNameMatch ? fileNameMatch : null;
    },

    async handleDownloadError(error) {
      if (error.response?.data instanceof Blob) {
        try {
          const text = await new Response(error.response.data).text();
          const result = JSON.parse(text);
          this.$message.error(result.msg || '文件下载失败');
        } catch {
          this.$message.error('文件下载失败');
        }
      } else {
        this.$message.error(error.message || '网络连接异常');
      }
    },

    // 通用方法
    handleQuery() {
      this.pagination.page = 1;
      this.fetchTaskList();
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchTaskList();
    },

    handleCurrentChange(val) {
      this.pagination.page = val;
      this.fetchTaskList();
    },

    formatCategory(val) {
      return val === 0 ? '统计' : '预测';
    },

    formatState(val) {
      const states = ['进行中', '成功', '失败'];
      return states[val] || '未知状态';
    },

    formatSource(val) {
      return val === 0 ? '系统生成' : '用户创建';
    },

    stateTagType(val) {
      return val === 0 ? 'warning' : val === 1 ? 'success' : 'danger';
    }
  }
};
</script>


<style scoped lang="scss">
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }

  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }

  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans",
  "Helvetica Neue",
  Helvetica,
  Arial,
  sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
.task-list-container {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
